import { useState, useEffect } from 'react';
import { exerciseAPI, submissionAPI } from '../services/api';

function WritingPractice({ onNavigateToHistory }) {
  const [exercise, setExercise] = useState(null);
  const [content, setContent] = useState('');
  const [wordCount, setWordCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);

  // 加载随机题目
  useEffect(() => {
    loadRandomExercise();
  }, []);

  // 实时计算字数
  useEffect(() => {
    const words = content.trim().split(/\s+/).filter(word => word.length > 0);
    setWordCount(words.length);
  }, [content]);

  // 加载随机题目
  const loadRandomExercise = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await exerciseAPI.getRandomExercise();
      setExercise(response.data);
    } catch (err) {
      setError('加载题目失败，请重试');
      console.error('加载题目错误:', err);
    } finally {
      setLoading(false);
    }
  };

  // 提交写作
  const handleSubmit = async () => {
    if (!content.trim()) {
      alert('请输入您的作文内容');
      return;
    }

    if (wordCount < 50) {
      alert('作文字数不能少于50字');
      return;
    }

    if (content.length > 5000) {
      alert('作文字数不能超过5000字符');
      return;
    }

    try {
      setSubmitting(true);
      setError(null);

      // 提交写作内容
      const submitResponse = await submissionAPI.createSubmission({
        exerciseId: exercise._id,
        content: content.trim(),
      });

      // 等待评分完成
      const submissionId = submitResponse.data.submissionId;
      await pollSubmissionResult(submissionId);
    } catch (err) {
      console.error('提交错误:', err);
      
      // 根据错误类型显示不同的错误信息
      if (err.response?.data?.message) {
        setError(err.response.data.message);
      } else if (err.response?.status === 500) {
        setError('服务器内部错误，请稍后重试');
      } else if (err.response?.status === 400) {
        setError('请求参数错误，请检查输入内容');
      } else if (err.code === 'NETWORK_ERROR') {
        setError('网络连接失败，请检查网络后重试');
      } else {
        setError('提交失败，请重试');
      }
    } finally {
      setSubmitting(false);
    }
  };

  // 轮询获取评分结果
  const pollSubmissionResult = async (submissionId) => {
    const maxAttempts = 30;
    let attempts = 0;

    const poll = async () => {
      try {
        const response = await submissionAPI.getSubmission(submissionId);
        const submission = response.data;

        if (submission.status === 'completed') {
          setResult(submission);
          return;
        }

        if (submission.status === 'failed') {
          setError('评分失败，请重试');
          return;
        }

        // 继续轮询
        attempts++;
        if (attempts < maxAttempts) {
          setTimeout(poll, 1000);
        } else {
          setError('评分超时，请稍后查看历史记录');
        }
      } catch (err) {
        console.error('获取评分结果错误:', err);
        setError('获取评分结果失败');
      }
    };

    await poll();
  };

  // 重新开始
  const handleReset = () => {
    setContent('');
    setWordCount(0);
    setResult(null);
    setError(null);
    loadRandomExercise();
  };

  // 查看历史记录
  const handleViewHistory = () => {
    if (onNavigateToHistory) {
      onNavigateToHistory();
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen bg-gradient-to-br from-gray-50 to-blue-50">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-600 mb-4"></div>
          <p className="text-xl text-gray-600 font-medium">加载题目中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 py-8">
      <div className="max-w-7xl mx-auto px-4">
        {/* 页面标题 */}
        <div className="text-center mb-10">
          <div className="inline-flex items-center justify-center mb-4">
            <div className="bg-gradient-to-r from-blue-600 to-indigo-600 text-white p-4 rounded-2xl shadow-lg">
              <span className="text-5xl">✍️</span>
            </div>
          </div>
          <h1 className="text-5xl font-extrabold bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent mb-3">
            雅思写作练习
          </h1>
          <p className="text-xl text-gray-600 font-medium">IELTS Writing Practice</p>
          <div className="mt-4 inline-block bg-white px-6 py-2 rounded-full shadow-md border-2 border-blue-100">
            <span className="text-sm text-gray-600">📊 提升您的写作技能，冲刺雅思高分</span>
          </div>
        </div>

        {error && (
          <div className="max-w-5xl mx-auto mb-6 bg-gradient-to-r from-red-50 to-pink-50 border-l-4 border-red-500 text-red-700 px-6 py-4 rounded-r-xl shadow-lg flex items-center">
            <span className="text-2xl mr-3">⚠️</span>
            <span className="font-semibold">{error}</span>
          </div>
        )}

        {!result ? (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* 左侧：题目区域 */}
            <div className="lg:col-span-1">
              {/* 题目显示区域 */}
              {exercise && (
                <div className="bg-white rounded-2xl shadow-2xl border-2 border-blue-100 sticky top-6">
                  {/* 题目标题栏 */}
                  <div className="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-6 py-4 rounded-t-2xl">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center">
                        <span className="text-3xl mr-3">📄</span>
                        <div>
                          <h3 className="text-sm font-medium opacity-90">考试题目</h3>
                          <h2 className="text-xl font-bold">{exercise.title}</h2>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* 题目内容 */}
                  <div className="p-6">
                    {/* 标签 */}
                    <div className="flex gap-2 mb-4">
                      <span className="px-3 py-1.5 bg-gradient-to-r from-blue-100 to-blue-200 text-blue-800 rounded-lg text-xs font-bold uppercase tracking-wide">
                        {exercise.type}
                      </span>
                      <span className={`px-3 py-1.5 rounded-lg text-xs font-bold uppercase tracking-wide ${
                        exercise.difficulty === 'easy' ? 'bg-gradient-to-r from-green-100 to-green-200 text-green-800' :
                        exercise.difficulty === 'medium' ? 'bg-gradient-to-r from-yellow-100 to-yellow-200 text-yellow-800' :
                        'bg-gradient-to-r from-red-100 to-red-200 text-red-800'
                      }`}>
                        {exercise.difficulty}
                      </span>
                    </div>

                    {/* 题目正文 */}
                    <div className="bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 rounded-xl p-5 mb-5 border-2 border-blue-100">
                      <p className="text-gray-800 leading-relaxed text-base font-medium">
                        {exercise.content}
                      </p>
                    </div>

                    {/* 要求信息 */}
                    <div className="space-y-3">
                      <div className="bg-white border-2 border-orange-200 rounded-xl p-4">
                        <div className="flex items-center">
                          <div className="bg-orange-100 p-2 rounded-lg mr-3">
                            <span className="text-2xl">⏱️</span>
                          </div>
                          <div>
                            <p className="text-xs text-gray-500 font-medium">建议时间</p>
                            <p className="text-lg font-bold text-gray-800">{exercise.timeLimit} 分钟</p>
                          </div>
                        </div>
                      </div>
                      <div className="bg-white border-2 border-green-200 rounded-xl p-4">
                        <div className="flex items-center">
                          <div className="bg-green-100 p-2 rounded-lg mr-3">
                            <span className="text-2xl">📝</span>
                          </div>
                          <div>
                            <p className="text-xs text-gray-500 font-medium">字数要求</p>
                            <p className="text-lg font-bold text-gray-800">至少 {exercise.wordLimit} 字</p>
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* 提示 */}
                    <div className="mt-5 bg-gradient-to-r from-yellow-50 to-amber-50 border-l-4 border-yellow-400 p-4 rounded-r-xl">
                      <div className="flex">
                        <span className="text-2xl mr-2">💡</span>
                        <div>
                          <p className="text-xs font-semibold text-yellow-800 mb-1">写作提示</p>
                          <p className="text-sm text-gray-700">注意论点清晰、逻辑连贯、语法准确</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* 右侧：答题区域 */}
            <div className="lg:col-span-2">
              <div className="bg-white rounded-2xl shadow-2xl border-2 border-indigo-100 overflow-hidden">
                {/* 答题区标题栏 */}
                <div className="bg-gradient-to-r from-indigo-600 to-purple-600 text-white px-6 py-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center">
                      <span className="text-3xl mr-3">✍️</span>
                      <div>
                        <h3 className="text-sm font-medium opacity-90">写作答题区</h3>
                        <h2 className="text-xl font-bold">Your Answer</h2>
                      </div>
                    </div>
                            <div className={`px-5 py-2.5 rounded-full font-bold text-lg shadow-lg backdrop-blur-sm ${
                              wordCount < 50 ? 'bg-red-500/90 text-white' :
                              wordCount < exercise?.wordLimit ? 'bg-yellow-400/90 text-gray-900' :
                              'bg-green-500/90 text-white'
                            }`}>
                              <div className="flex items-center gap-2">
                                <span className="text-sm opacity-90">字数</span>
                                <span className="text-2xl font-extrabold">{wordCount}</span>
                              </div>
                              <div className="text-xs opacity-75 mt-1">
                                {content.length}/5000 字符
                              </div>
                            </div>
                  </div>
                </div>

                {/* 答题内容区 */}
                <div className="p-6">
                  {/* 文本输入框 */}
                  <textarea
                    value={content}
                    onChange={(e) => setContent(e.target.value)}
                    placeholder="✨ 开始您的写作...

📌 写作建议：
• 引言段：简述背景，明确观点
• 主体段：2-3个论点，每个论点配合例证
• 结论段：总结观点，呼应主题

💡 评分要点：
• 任务完成度 - 回应题目所有要求
• 连贯性 - 逻辑清晰，过渡自然  
• 词汇丰富度 - 使用多样化表达
• 语法准确性 - 避免常见错误"
                    className="w-full h-[500px] p-6 bg-gradient-to-br from-white to-blue-50/30 border-2 border-indigo-200 rounded-2xl resize-none focus:ring-4 focus:ring-indigo-200 focus:border-indigo-400 transition-all outline-none text-gray-800 leading-relaxed text-lg font-medium shadow-inner"
                    disabled={submitting}
                  />

                  {/* 状态提示条 */}
                  <div className="mt-4 flex items-center justify-between bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-4 border border-indigo-100">
                    <div className="flex gap-3">
                      {wordCount < 50 && (
                        <span className="flex items-center text-red-600 font-semibold bg-red-50 px-4 py-2 rounded-lg border-2 border-red-200">
                          <span className="mr-2">❌</span>
                          字数不足
                        </span>
                      )}
                      {wordCount >= 50 && wordCount < exercise?.wordLimit && (
                        <span className="flex items-center text-yellow-700 font-semibold bg-yellow-50 px-4 py-2 rounded-lg border-2 border-yellow-200">
                          <span className="mr-2">⚠️</span>
                          继续加油
                        </span>
                      )}
                      {wordCount >= exercise?.wordLimit && content.length <= 5000 && (
                        <span className="flex items-center text-green-700 font-semibold bg-green-50 px-4 py-2 rounded-lg border-2 border-green-200 animate-pulse">
                          <span className="mr-2">✅</span>
                          字数达标！可以提交
                        </span>
                      )}
                      {content.length > 5000 && (
                        <span className="flex items-center text-red-600 font-semibold bg-red-50 px-4 py-2 rounded-lg border-2 border-red-200">
                          <span className="mr-2">⚠️</span>
                          字符数超限（{content.length}/5000）
                        </span>
                      )}
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex gap-3">
                      <button
                        onClick={handleViewHistory}
                        className="px-5 py-2.5 bg-white text-gray-700 rounded-xl hover:bg-gray-50 transition-all font-semibold border-2 border-gray-300 hover:border-gray-400 shadow-md hover:shadow-lg"
                      >
                        📚 历史记录
                      </button>
                      <button
                        onClick={handleSubmit}
                        disabled={submitting || !content.trim() || content.length > 5000}
                        className="px-8 py-2.5 bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 text-white rounded-xl hover:from-indigo-700 hover:via-purple-700 hover:to-pink-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all font-bold shadow-xl hover:shadow-2xl transform hover:-translate-y-1 hover:scale-105"
                      >
                        {submitting ? (
                          <span className="flex items-center">
                            <span className="animate-spin mr-2">⏳</span>
                            AI智能评分中...
                          </span>
                        ) : '🚀 提交并获取AI评分'}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <>
            {/* 评分结果展示 */}
            <div className="bg-white rounded-lg shadow-md p-6 mb-6">
              <h2 className="text-2xl font-bold text-center mb-6 text-gray-800">
                评分结果
              </h2>

              {/* 总分展示 */}
              <div className="text-center mb-8">
                <div className="text-6xl font-bold text-blue-600 mb-2">
                  {result.scores.overall}
                </div>
                <div className="text-gray-600">总分</div>
              </div>

              {/* 四个维度评分 */}
              <div className="grid grid-cols-2 gap-4 mb-6">
                <div className="bg-blue-50 p-4 rounded-lg">
                  <div className="text-2xl font-bold text-blue-600 mb-1">
                    {result.scores.taskAchievement}
                  </div>
                  <div className="text-gray-700">任务完成</div>
                </div>
                <div className="bg-green-50 p-4 rounded-lg">
                  <div className="text-2xl font-bold text-green-600 mb-1">
                    {result.scores.coherence}
                  </div>
                  <div className="text-gray-700">连贯性</div>
                </div>
                <div className="bg-purple-50 p-4 rounded-lg">
                  <div className="text-2xl font-bold text-purple-600 mb-1">
                    {result.scores.vocabulary}
                  </div>
                  <div className="text-gray-700">词汇</div>
                </div>
                <div className="bg-orange-50 p-4 rounded-lg">
                  <div className="text-2xl font-bold text-orange-600 mb-1">
                    {result.scores.grammar}
                  </div>
                  <div className="text-gray-700">语法</div>
                </div>
              </div>

              {/* AI反馈 */}
              <div className="bg-gray-50 p-4 rounded-lg mb-6">
                <h3 className="font-semibold text-gray-800 mb-2">📝 AI反馈</h3>
                <p className="text-gray-700 leading-relaxed">{result.feedback}</p>
              </div>

              {/* 优点和改进建议 */}
              {result.strengths && result.strengths.length > 0 && (
                <div className="bg-green-50 p-4 rounded-lg mb-4">
                  <h3 className="font-semibold text-green-800 mb-2">✅ 优点</h3>
                  <ul className="list-disc list-inside text-gray-700">
                    {result.strengths.map((strength, index) => (
                      <li key={index}>{strength}</li>
                    ))}
                  </ul>
                </div>
              )}

              {result.improvements && result.improvements.length > 0 && (
                <div className="bg-yellow-50 p-4 rounded-lg mb-6">
                  <h3 className="font-semibold text-yellow-800 mb-2">
                    💡 改进建议
                  </h3>
                  <ul className="list-disc list-inside text-gray-700">
                    {result.improvements.map((improvement, index) => (
                      <li key={index}>{improvement}</li>
                    ))}
                  </ul>
                </div>
              )}

              {/* 操作按钮 */}
              <div className="flex gap-3 justify-center">
                <button
                  onClick={handleViewHistory}
                  className="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
                >
                  查看历史
                </button>
                <button
                  onClick={handleReset}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  继续练习
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

export default WritingPractice;

